<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>库存管理系统</title>
    <!-- 引入Element UI样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f7fa;
        }
        .app-container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            padding: 20px;
            border-radius: 4px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .search-form {
            margin-bottom: 20px;
        }
        .action-buttons {
            margin-bottom: 20px;
        }
        .el-table {
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
<div id="app" class="app-container">
    <div class="header">
        <h2>库存管理系统</h2>
        <el-button
                type="primary"
                icon="el-icon-plus"
                size="medium"
                @click="showDialog('add')">
            新增库存
        </el-button>
    </div>

    <!-- 搜索表单 -->
    <el-form :model="queryParams" class="search-form" size="small" inline>
        <el-form-item label="库存ID">
            <el-input
                    v-model="queryParams.inventoryId"
                    placeholder="请输入库存ID"
                    clearable>
            </el-input>
        </el-form-item>
        <el-form-item label="产品ID">
            <el-input
                    v-model="queryParams.productId"
                    placeholder="请输入产品ID"
                    clearable>
            </el-input>
        </el-form-item>
        <el-form-item label="库存数量">
            <el-input
                    v-model="queryParams.quantity"
                    placeholder="请输入库存数量"
                    clearable>
            </el-input>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="getInventoryList">搜索</el-button>
            <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div class="action-buttons">

    </div>

    <!-- 库存列表表格 -->
    <el-table
            :data="inventoryList"
            style="width: 100%"
            v-loading="loading"
            border
            stripe
            @selection-change="handleSelectionChange">
        <el-table-column
                type="selection"
                width="55"
                align="center">
        </el-table-column>
        <el-table-column
                prop="inventoryId"
                label="库存ID"
                width="120"
                align="center">
        </el-table-column>
        <el-table-column
                prop="productId"
                label="产品ID"
                width="120"
                align="center">
        </el-table-column>
        <el-table-column
                prop="quantity"
                label="库存数量"
                width="120"
                align="center">
        </el-table-column>
        <el-table-column
                prop="location"
                label="库存位置"
                align="center">
        </el-table-column>
        <el-table-column
                label="修改时间"
                width="180"
                align="center">
            <template slot-scope="scope">
                {{ formatDate(scope.row.updateTime) }}
            </template>
        </el-table-column>
        <el-table-column
                label="操作"
                width="180"
                align="center"
                class-name="action-buttons">
            <template slot-scope="scope">
                <el-button
                        size="mini"
                        @click="showDialog('edit', scope.row)">
                    编辑
                </el-button>
                <el-button
                        size="mini"
                        type="danger"
                        @click="handleDelete(scope.row)">
                    删除
                </el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryParams.pageNum"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="queryParams.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
    </el-pagination>

    <!-- 库存对话框（新增/编辑） -->
    <el-dialog
            :title="dialogTitle"
            :visible.sync="dialogVisible"
            width="500px"
            :close-on-click-modal="false">
        <el-form
                :model="formData"
                :rules="rules"
                ref="inventoryForm"
                label-width="100px">
            <el-form-item
                    label="产品ID："
                    prop="productId">
                <el-input
                        v-model="formData.productId"
                        placeholder="请输入产品ID"
                        clearable>
                </el-input>
            </el-form-item>
            <el-form-item
                    label="库存数量："
                    prop="quantity">
                <el-input
                        v-model="formData.quantity"
                        placeholder="请输入库存数量"
                        type="number"
                        clearable>
                </el-input>
            </el-form-item>
            <el-form-item
                    label="库存位置："
                    prop="location">
                <el-input
                        v-model="formData.location"
                        placeholder="请输入库存位置"
                        clearable>
                </el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button
                    type="primary"
                    @click="submitForm"
                    :loading="submitting">
                {{ dialogType === 'add' ? '新增' : '保存' }}
            </el-button>
        </div>
    </el-dialog>
</div>

<!-- 引入Vue和Element UI -->
<script src="https://unpkg.com/vue@2.6.14/dist/vue.js"></script>
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script src="../../plugins/axios/axios.min.js"></script>
<script src="https://unpkg.com/dayjs@1.10.7/dayjs.min.js"></script>
<script>
    new Vue({
        el: '#app',
        data() {
            return {
                loading: false,          // 表格加载状态
                submitting: false,       // 提交按钮加载状态
                dialogVisible: false,    // 对话框显示状态
                dialogType: 'add',       // 对话框类型：add/edit
                dialogTitle: '新增库存', // 对话框标题
                inventoryList: [],      // 库存列表数据
                selectedRows: [],        // 选中的行数据
                total: 0,               // 总条数
                queryParams: {           // 查询参数
                    pageNum: 1,
                    pageSize: 10,
                    inventoryId: '',
                    productId: '',
                    quantity: '',
                    location: ''
                },
                formData: {              // 表单数据
                    inventoryId: '',
                    productId: '',
                    quantity: '',
                    location: ''
                },
                rules: {                 // 表单验证规则
                    productId: [
                        { required: true, message: '请输入产品ID', trigger: 'blur' }
                    ],
                    quantity: [
                        { required: true, message: '请输入库存数量', trigger: 'blur' },
                        { pattern: /^[1-9]\d*$/, message: '请输入正整数', trigger: 'blur' }
                    ],
                    location: [
                        { required: true, message: '请输入库存位置', trigger: 'blur' }
                    ]
                }
            };
        },
        created() {
            // 组件创建时加载库存列表
            this.getInventoryList();
        },
        methods: {
            // 获取库存列表
            getInventoryList() {
                this.loading = true;
                const params = {
                    pageNum: this.queryParams.pageNum,
                    pageSize: this.queryParams.pageSize,
                    inventoryId: this.queryParams.inventoryId || null,
                    productId: this.queryParams.productId || null,
                    quantity: this.queryParams.quantity || null,
                    location: this.queryParams.location || null
                };

                axios.get('/component/inventory/list', { params })
                    .then(response => {
                        if (response.data && response.data.code === 200) {
                            this.inventoryList = response.data.data.records || [];
                            this.total = response.data.data.total || 0;
                        } else {
                            this.inventoryList = [];
                            this.total = 0;
                            this.$message.error(response.data.msg || "获取数据失败");
                        }
                    })
                    .catch(error => {
                        console.error('获取库存列表失败:', error);
                        this.$message.error('获取库存列表失败: ' + (error.response?.data?.message || error.message));
                        this.inventoryList = [];
                        this.total = 0;
                    })
                    .finally(() => {
                        this.loading = false;
                    });
            },

            // 显示对话框
            showDialog(type, row) {
                this.dialogType = type;
                this.dialogTitle = type === 'add' ? '新增库存' : '编辑库存';

                if (type === 'add') {
                    // 新增模式，重置表单
                    this.formData = {
                        inventoryId: '',
                        productId: '',
                        quantity: '',
                        location: ''
                    };
                } else {
                    // 编辑模式，填充表单数据
                    this.formData = {
                        inventoryId: row.inventoryId,
                        productId: row.productId,
                        quantity: row.quantity,
                        location: row.location
                    };
                }

                this.dialogVisible = true;

                // 清除验证状态
                this.$nextTick(() => {
                    if (this.$refs.inventoryForm) {
                        this.$refs.inventoryForm.clearValidate();
                    }
                });
            },

            // 提交表单（新增/编辑）
            submitForm() {
                this.$refs.inventoryForm.validate(valid => {
                    if (valid) {
                        this.submitting = true;

                        const isAdd = this.dialogType === 'add';
                        const request = isAdd
                            ? axios.post('/component/inventory', this.formData)
                            : axios.put('/component/inventory', this.formData);

                        request.then(response => {
                            this.$message.success(isAdd ? '新增库存成功' : '更新库存成功');
                            this.dialogVisible = false;
                            this.getInventoryList(); // 刷新列表
                        })
                            .catch(error => {
                                this.$message.error((isAdd ? '新增' : '更新') + '库存失败: ' +
                                    (error.response?.data?.message || error.message));
                            })
                            .finally(() => {
                                this.submitting = false;
                            });
                    }
                });
            },

            // 删除库存
            handleDelete(row) {
                this.$confirm('确定要删除该库存记录吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.loading = true;
                    axios.delete(`/component/inventory/${row.inventoryId}`)
                        .then(response => {
                            this.$message.success('删除库存成功');
                            this.getInventoryList(); // 刷新列表
                        })
                        .catch(error => {
                            this.$message.error('删除库存失败: ' +
                                (error.response?.data?.message || error.message));
                        })
                        .finally(() => {
                            this.loading = false;
                        });
                }).catch(() => {
                    // 用户取消删除
                });
            },

            // 批量删除
            handleBatchDelete() {
                if (!this.selectedRows || this.selectedRows.length === 0) {
                    this.$message.warning('请至少选择一条记录');
                    return;
                }

                const inventoryIds = this.selectedRows.map(item => item.inventoryId);
                this.$confirm('确定要删除选中的库存记录吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.loading = true;
                    axios.delete(`/component/inventory/${inventoryIds.join(',')}`)
                        .then(response => {
                            this.$message.success('删除库存成功');
                            this.getInventoryList();
                        })
                        .catch(error => {
                            this.$message.error('删除库存失败: ' + (error.response?.data?.message || error.message));
                        })
                        .finally(() => {
                            this.loading = false;
                        });
                }).catch(() => {
                    // 用户取消删除
                });
            },

            // 格式化日期显示
            formatDate(date) {
                if (!date) return '-';  // 如果日期为空，返回 -
                return dayjs(date).format('YYYY-MM-DD HH:mm:ss');  // 使用 dayjs 格式化日期
            },

            // 处理选中行变化
            handleSelectionChange(selection) {
                this.selectedRows = selection;
            },

            // 分页大小改变
            handleSizeChange(val) {
                this.queryParams.pageSize = val;
                this.getInventoryList();
            },

            // 当前页改变
            handleCurrentChange(val) {
                this.queryParams.pageNum = val;
                this.getInventoryList();
            },

            // 重置查询
            resetQuery() {
                this.queryParams = {
                    pageNum: 1,
                    pageSize: 10,
                    inventoryId: '',
                    productId: '',
                    quantity: '',
                    location: ''
                };
                this.getInventoryList();
            }
        }
    });
</script>
</body>
</html>